<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/6/8
 * Time: 下午5:36
 */
namespace App\Api\Controllers\EasyPay;


use function EasyWeChat\Kernel\Support\get_client_ip;
use Illuminate\Support\Facades\Log;

class PayController extends BaseController
{

    //统一下单支付  -1 系统错误 0-其他 1-成功
    public function scan_pay22($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $code = $data['code'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $trade_amt = isset($total_amount) ? ($total_amount*100) : '';
            $term_id = $data['device_id'] ?? '';
            $shop_name = $data['shop_name'] ?? '';
            $notify_url = $data['notify_url'] ?? '';
            $pay_type = $data['pay_type'] ?? '';
            $mer_id = $data['mno'] ?? '';

            if ($pay_type == 'alipay') {
                $opt = 'apPreOrder';
            }
            elseif($pay_type == 'weixin') {
                $opt = 'wxPreOrder';
            }
            elseif($pay_type == 'unionpay') {
                $opt = 'upPreOrder';
            }
            else {
                $opt = '';
            }

            $easypay_data = [
                'channelid' => $channel_id, //是,渠道编号
                'merid' => $mer_id, //是,商户编号
                'termid' => $term_id, //是,终端编号
                'tradetrace' => $out_trade_no, //是,商户订单号（控制在 50 位长度以内，确保在请求接口的系统中全局唯一；可以包含数字与字母；不能包含其他特殊字符）
                'opt' => $opt, //是,操作类型（“wxPreOrder”：微信；“apPreOrder”：支付宝；“upPreOrder”：银联），根据实际情况选其一
                'tradetype' => 'JSAPI', //是,支付方式（“NATIVE”：线下扫码/原生支付[微信不支持]；“JSAPI”：网页内支付）
                'tradeamt' => $trade_amt, //是,交易金额（单位：分）
                'body' => $shop_name, //是,商品或支付单简要描述（给用户看）
                'openid' => $code, //tradetype=JSAPI，此参数必传,支付宝（买家支付宝用户 ID，参考文档 ）；微信（用户在商户sub_appid[支付的公众号] 下的唯一标识，参考文档 ）
                'notifyurl' => $notify_url, //是,客户端接收微信支付成功通知的地址，通知报文请见“后台通知接口”
                'returnurl' => ($pay_type == 'unionpay') ? '':'', //否,交易成功后的前台接收地址。当提交的是银联行业码预下单交易（opt 为upPreOrder,为 tradetype 是 JSAPI），本节点必填???
                'customerip' => get_client_ip(), //否,持卡人确认付款时的 IP 地址,用于防钓鱼。需注意:无代理情况通过‘REMOTE_ADDR’获取 IP 地址,有代理情况通过‘REAL_IP’获取真实 IP地址。当提交的是银联行业码预下单交易（opt 为 upPreOrder,为tradetype 是 JSAPI），本节点必填。
//                'handingfee' => $handingfee, //否,手续费（以分为单位,第一位是 D 或 C，表示借、贷）
                'version' => '2', //否,填写的值为 2 时，交易成功后返回优惠信息
            ];
            Log::info('易生支付-静态二维码');
            Log::info($easypay_data);
//            Log::info($this->signKey);
            $res_obj = $this->payment->request($easypay_data, $this->signKey);
            Log::info($res_obj);

            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }

            $res_arr = json_decode($res_obj, true);

            //成功
            if ($res_arr['resultcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => '返回成功',
                    'code_url' => $res_arr['codeurl'],
                    'data' => $res_arr['data']
                ];
            } //TODO：其他码暂不清楚
            else {
                return [
                    'status' => '0',
                    'message' => $res_arr['returnmsg'],
                    'data' => $res_arr
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-静态二维码');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


      //被扫(付款码支付) -1 系统错误 0-其他 1-成功 2-待支付
    public function scan_pay($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mno'] ?? '';
            $term_id = $data['device_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
//            $trade_amt = isset($total_amount) ? ($total_amount*100) : '';
            $code = $data['code'] ?? '';
            $shop_name = $data['shop_name'] ?? '';
            $trade_amt = bcmul($data['total_amount'], 100);
            $easypay_data = [
                "data" => [
                    "authCode" => $code,
                    "orderInfo" => $shop_name,
                    "tradeAmt" => $trade_amt,
                    "patnerSettleFlag"=>1,
                ],
                "orgMercode" => $mer_id, //商户号
                "orgTermno" => $term_id, //终端号
                "orgTrace" => $out_trade_no,
            ];
            $settlement_type=$data['settlement_type'] ?? '';
            if($settlement_type=="D0"){
                $easypay_data["data"]["patnerSettleFlag"]="0";
            }
            $base = NewBaseController::getInstance();

            /* 备份
            $res_obj = $base->params($easypay_data, $easypay_data['data'], $data['private_key'], $channel_id)
                ->build($base::MIAN.':'.$base::PROD1.'/'.$base::SCAN_PAY, 'post');
            */
            $requestUrl=$base::DOMAIN."/".$base::SCAN_PAY;
            $res_obj = $base->params($easypay_data, $easypay_data['data'], $data['private_key'], $channel_id)->build($requestUrl, 'post');
//            error_log(date('Y-m-d H:i:s')." 【易生被扫】： ".json_encode([$easypay_data, $res_obj])."\n\n", 3, "/tmp/". 'easypay'.date('Ymd').".log");
            Log::channel("easypay")->info("scan_pay",[
                "url"=>$requestUrl,
                "data"=>$easypay_data,
                "res"=>[$res_obj]
            ]);
            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }


            //成功
            if ($res_obj['data']['finRetcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => '交易成功',
                    'data' => $res_obj['data'],
                ];
            }
            //待支付
            elseif ($res_obj['data']['finRetcode'] == '99') {
                return [
                    'status' => '2',
                    'message' => '待支付',
                    'data' => $res_obj,
                ];
            }
            //TODO：其他码暂不清楚
            else {
                return [
                    'status' => '0',
                    'message' => $res_obj['data']['appendRetmsg'] ?? 'UNKNOWN',
                    'data' => $res_obj
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-被扫错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


    //查询订单 -1 系统错误 0-其他 1-成功 2-下单失败 3-订单未支付
    public function order_query($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mno'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $term_id = $data['device_id'] ?? '';
            $easypay_data = [
                "data" => [
                    "oriOrgTrace" => $out_trade_no
                ],
                "orgMercode" => $mer_id, //商户号
                "orgTermno" => $term_id, //终端号
                "orgTrace" => date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)).rand(10,99),
            ];
//error_log(date('Y-m-d H:i:s')." 【易生支付查询1】： ".json_encode([$easypay_data, get_client_ip()])."\n\n", 3, "/www/wwwlogs/wft/". 'prod-easy-pay'.date('Ymd').".log");
            $base = NewBaseController::getInstance();

            $requestUrl=$base::DOMAIN."/".$base::ORDER_QUERY;
            /**
            $res_obj = $base->params($easypay_data, $easypay_data['data'],$data['private_key'], $channel_id)->build($base::MIAN.':'.$base::PROD1.'/'.$base::ORDER_QUERY, 'post');
             */
            $res_obj = $base->params($easypay_data, $easypay_data['data'],$data['private_key'], $channel_id)->build($requestUrl, 'post');
            Log::channel("easypay")->info("order_query",[
                "url"=>$requestUrl,
                "data"=>$easypay_data,
                "res"=>[$res_obj]
            ]);
 //error_log(date('Y-m-d H:i:s')." 【易生支付查询2】： ".json_encode([$res_obj])."\n\n", 3, "/www/wwwlogs/wft/". 'prod-easy-pay'.date('Ymd').".log");
            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }

            if ($res_obj['sysRetcode'] != '000000') {
                return [
                    'status' => '0',
                    'message' => $res_obj['sysRetmsg'] ?? 'UNKNOWN'
                ];
            }

            //交易成功
            if ($res_obj['data']['finRetcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => '查询成功',
                    'data' => $res_obj['data'],
                ];
            }  elseif ($res_obj['data']['finRetcode'] == '99') {
                return [
                    'status' => '2',
                    'message' => '待支付',
                    'data' => $res_obj,
                ];
            } elseif ($res_obj['data']['finRetcode'] == 'AA') {
                return [
                    'status' => '3',
                    'message' => '订单未支付',
                    'data' => $res_obj
                ];
            }
            else {
                return [
                    'status' => '0',
                    'message' => $res_obj['data']['appendRetmsg'] ?? 'UNKNOWN'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-交易查询-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


    //退款（支持对原交易的部分金额退货）-1 系统错误 0-其他 1-成功 2-失败
    public function refund($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mer_id'] ?? '';
            $term_id = $data['term_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $refund_amount = isset($data['refund_amount']) ? ($data['refund_amount']*100) : '';
            $return_no = $out_trade_no . rand(1000, 9999);


            $easypay_data = [
                "bizData" => [
                    "oriOrgTrace" => $out_trade_no,
                    "transAmt" => (string)$refund_amount
                ],
                "orgMercode" => $mer_id, //商户号
                "orgTermno" => $term_id, //终端号
                "orgTrace" => $return_no,
            ];

            $base = NewBaseController::getInstance();

            $requestUrl=$base::DOMAIN."/".$base::REFUND;

            /*
            $res_obj = $base->params($easypay_data, $easypay_data['bizData'], $data['private_key'], $channel_id)->build($base::MIAN.':'.$base::PROD2.'/'.$base::REFUND, 'post');
            */
            $res_obj = $base->params($easypay_data, $easypay_data['bizData'], $data['private_key'], $channel_id)->build($requestUrl, 'post');
            Log::channel("easypay")->info("refund",[
                "url"=>$requestUrl,
                "data"=>$easypay_data,
                "res"=>[$res_obj]
            ]);
            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }

            if ($res_obj['sysRetCode'] == '00') {
                if ($res_obj['bizData']['tradeRetCode'] == '00') {
                    return [
                        'status' => '1',
                        'message' => $res_arr['returnmsg'] ?? '退款成功',
                        'data' => $res_obj,
                    ];
                } else {
                    return [
                        'status' => '2',
                        'message' => $res_obj['tradeRetMsg'] ?? '退款失败',
                        'data' => [],
                    ];
                }
            } else {
                return [
                    'status' => '2',
                    'message' => $res_obj['sysRetMsg'] ?? '退款失败',
                    'data' => [],
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-退款-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }

    public function refund_query($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mer_id'] ?? '';
            $term_id = $data['term_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';


            $easypay_data = [
                "bizData" => [
                    "oriOrgTrace" => $data['refund_no']
                ],
                "orgMercode" => $mer_id, //商户号
                "orgTermno" => $term_id, //终端号
                "orgTrace" => $out_trade_no,
            ];

            $base = NewBaseController::getInstance();


            $requestUrl=$base::DOMAIN."/".$base::REFUND_QUERY;

            /*
            $res_obj = $base->params($easypay_data, $easypay_data['bizData'], $data['private_key'], $channel_id)->build($base::MIAN.':'.$base::PROD2.'/'.$base::REFUND_QUERY, 'post');
            */
            $res_obj = $base->params($easypay_data, $easypay_data['bizData'], $data['private_key'], $channel_id)->build($requestUrl, 'post');
            //系统错误
            Log::channel("easypay")->info("refund_query",[
                "url"=>$requestUrl,
                "data"=>$easypay_data,
                "res"=>[$res_obj]
            ]);
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }

            if ($res_obj['sysRetCode'] == '00') {
                if ($res_obj['bizData']['tradeRetCode'] == '00') {
                    return [
                        'status' => '1',
                        'message' => $res_arr['returnmsg'] ?? '退款成功',
                        'data' => $res_obj,
                    ];
                } else {
                    return [
                        'status' => '2',
                        'message' => $res_obj['tradeRetMsg'] ?? '退款失败',
                        'data' => [],
                    ];
                }
            } else {
                return [
                    'status' => '2',
                    'message' => $res_obj['sysRetMsg'] ?? '退款失败',
                    'data' => [],
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-退款-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


    //被扫(付款码支付) -1 系统错误 0-其他 1-成功 2-待支付
    public function scan_pay1($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mno'] ?? '';
            $term_id = $data['device_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $trade_amt = isset($total_amount) ? ($total_amount*100) : '';
            $code = $data['code'] ?? '';
            $shop_name = $data['shop_name'] ?? '';

            $easypay_data = [
                'channelid' => $channel_id, //是,渠道编号
                'merid' => $mer_id, //是,商户编号
                'termid' => $term_id, //是,终端编号
                'tradetrace' => $out_trade_no, //是,商户订单号（控制在 50 位长度以内，确保在请求接口的系统中全局唯一；可以包含数字与字母；不能包含其他特殊字符）
                'opt' => 'scanPay', //是,操作类型（scanPay）
                'tradeamt' => $trade_amt, //是,交易金额（单位：分）
                'authcode' => $code, //是,扫码支付授权码，设备读取用户微信、支付宝、银联钱包中的条码或者二维码信息
                'body' => $shop_name, //是,商品或支付单简要描述（给用户看）
                'version' => '2', //否,填写的值为 2 时，交易成功后返回优惠信息
//                'handingfee' => $handingfee, //否,手续费（以分为单位,第一位是 D 或 C，表示借、贷）
            ];
            Log::info('易生支付-被扫2');
            Log::info($easypay_data);
//            Log::info($this->signKey);
            $res_obj = $this->payment->request($easypay_data, $this->signKey);
            Log::info($res_obj);

            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }

            $res_arr = json_decode($res_obj, true);

            //成功
            if ($res_arr['resultcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => $res_arr['returnmsg'] ?? '交易成功',
                    'data' => $res_arr,
                ];
            }
            //待支付
            elseif ($res_arr['resultcode'] == 'AA') {
                return [
                    'status' => '2',
                    'message' => '待支付',
                    'data' => $res_arr,
                ];
            }
            //TODO：其他码暂不清楚
            else {
                return [
                    'status' => '0',
                    'message' => $res_arr['returnmsg'] ?? 'UNKNOWN',
                    'data' => $res_arr
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-被扫错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


    //查询订单 -1 系统错误 0-其他 1-成功 2-下单失败 3-订单未支付
    public function order_query1($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mer_id'] ?? '';
            $device_id = $data['device_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';

            $select_data = [
                'channelid' => $channel_id, //渠道编号
                'merid' => $mer_id, //商戶编号
                'termid' => $device_id, //终端编号
                'tradetrace' => $out_trade_no, //原交易流水
                'opt' => 'tradeQuery', //操作类型（tradeQuery）
                //'tradetype' => '', //否,交易类型（“samecardQuery”：同名卡转出查询；其他查询为空）
            ];
            Log::info('易生支付-查询订单');
            Log::info($select_data);
////            Log::info($this->signKey);
            $res_obj = $this->payment->request($select_data, $this->signKey);
            Log::info($res_obj);

            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }

            $res_arr = json_decode($res_obj, true);

            //交易成功
            if ($res_arr['resultcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => $res_arr['returnmsg'] ?? '查询成功',
                    'data' => $res_arr,
                ];
            } elseif ($res_arr['resultcode'] == '06') {
                return [
                    'status' => '2',
                    'message' => '下单失败',
                    'data' => $res_arr,
                ];
            } elseif ($res_arr['resultcode'] == 'AA') {
                return [
                    'status' => '3',
                    'message' => '订单未支付',
                    'data' => $res_arr
                ];
            }
            else {
                return [
                    'status' => '0',
                    'message' => $res_arr['returnmsg'] ?? 'UNKNOWN'
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-交易查询-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


    //退款（支持对原交易的部分金额退货）-1 系统错误 0-其他 1-成功 2-失败
    public function refund1($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mer_id'] ?? '';
            $term_id = $data['term_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $trade_no = $data['trade_no'] ?? '';
            $refund_amount = isset($data['refund_amount']) ? ($data['refund_amount']*100) : '';
            $return_no = $trade_no . rand(1000, 9999);

            $return_data = [
                'channelid' => $channel_id, //渠道编号
                'merid' => $mer_id, //商戶编号
                'termid' => $term_id, //终端编号
                'tradetrace' => $return_no, //商户订单号（控制在 50 位长度以内，确保在请求接口的系统中全局唯一；可以包含数字与字母；不能包含其他特殊字符）
                'opt' => 'zwrefund', //操作类型（zwrefund）
                'oriwtorderid' => $trade_no, //原交易的系统订单号
                'tradeamt' => $refund_amount, //退货金额,以分为单位，不大于原交易金额与已成功退货金额之差
//                'notifymobileno' => '', //否,商户的通知手机 ,用于接收退货进展的通知短信（待完善）
//                'notifyusername' => '', //否,用于接收退货进展的通知短信（待完善）
            ];
            Log::info('易生支付-退款');
            Log::info($return_data);
//            Log::info($this->signKey);
            $res_obj = $this->payment->request($return_data, $this->signKey);
            Log::info($res_obj);

            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误'
                ];
            }

            $res_arr = json_decode($res_obj, true);

            //业务成功
            if ($res_arr['resultcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => $res_arr['returnmsg'] ?? '退款成功',
                    'data' => $res_arr,
                ];
            }
            elseif ($res_arr['resultcode'] == '93') {
                return [
                    'status' => '2',
                    'message' => $res_arr['returnmsg'] ?? '退款失败',
                    'data' => $res_arr,
                ];
            }
            elseif ($res_arr['resultcode'] == 'W5') {
                return [
                    'status' => '2',
                    'message' => $res_arr['returnmsg'] ?? '交易日期不符合要求,不能进行该操作',
                    'data' => $res_arr,
                ];
            }
            else {
                //退款失败，查询退款结果
//                $return_select_data = [
//                    'channel_id' => $channel_id,
//                    'out_trade_no' => $out_trade_no,
//                    'mer_id' => $mer_id,
//                    'device_id' => $term_id
//                ];
//                $return_select_arr = $this->order_query($return_select_data); //-1 系统错误 0-其他 1-成功 2-下单失败
//
//                if ($return_select_arr['status'] == '1') {
//                    return [
//                        'status' => '0',
//                        'message' => $return_select_arr['returnmsg'] ?? '查询成功',
//                        'data' => $return_select_arr
//                    ];
//                }

                return [
                    'status' => '0',
                    'message' => $res_arr['returnmsg'] ?? '退款失败',
                    'data' => $res_arr
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-退款-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


    //上传图片  -1 系统错误 0-其他 1-成功
    public function upload_image($data)
    {
        $key = $data['key'] ?? '';
        $file_name = $data['file_name'] ?? '';
        $client_code = $data['client_code'] ?? '';
        $image_type = $data['image_type'];

        $obj = new BaseController();

        $data = [
            'version' => '1.0', //版本号
            'fileName' => $file_name, //图片文件,该字段不参与签名
            'clientCode' => $client_code, //机构号,该字段由易生配置
            'MAC' => md5($file_name), //MAC值???
            'picMode' => $image_type, //图片类型,01 - 法人身份证正面 ；02-法人身份证反面；03-商户联系人身份证正面；04-商户联系人身份证反面；05-营业执照；06-收银台；07-内部环境照；08-营业场所门头照；09-门牌号；10-协议；11-商户登记表正面；12-商户登记表反面；13-开户许可证；14-银行卡；15-清算授权书；16-定位照（选填）；17-手持身份证照片（选填）
//               'customInfo' => '0', //自定义域
        ];

        try {
            $params = array_filter($data);
            $new_params = $params;
            unset($new_params['fileName']);
            unset($new_params['MAC']);
            $params['sign'] = $this->sign($new_params, $key);
            $ch = curl_init($obj->upload_image);
//            curl_setopt($ch, CURLOPT_URL, $obj->upload_image); //
//            curl_setopt($ch, CURLOPT_POST, 1); //启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); //使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); //JSON类型字符串
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type=multipart/form-data;charset=UTF-8'));
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //本地忽略校验证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $result = curl_exec($ch);
//var_dump($result);die;
            $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($result == NULL) {
                curl_close($ch);
                return [
                    'status' => '0',
                    'message' => '系统错误'
                ];
            } else if($response != '200'){
                $error = curl_errno($ch);
                curl_close($ch);
                return [
                    'status' => '0',
                    'message' => $error
                ];
            }
            curl_close($ch);
            return [
                'status' => '1',
                'data' => json_decode($result, true),
                'message' => '成功'
            ];

        } catch (\Exception $ex) {
            Log::info('易生支付-图片上传');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine()
            ];
        }
    }


    //交易撤销(仅对当日交易可以撤销，日切时间为渠道服务器的 00:00) -1 系统错误 0-其他 1-成功
    public function order_close($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mno'] ?? '';
            $term_id = $data['device_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $trade_no = $data['trade_no'] ?? '';
            $return_no = $out_trade_no . rand(1000, 9999);

            $easypay_data = [
                'channelid' => $channel_id, //是,渠道编号
                'merid' => $mer_id, //是,商户编号
                'termid' => $term_id, //是,终端编号
                'tradetrace' => $return_no, //是,商户订单号（控制在 50 位长度以内，确保在请求接口的系统中全局唯一；可以包含数字与字母；不能包含其他特殊字符）
                'opt' => 'cancel', //是,操作类型（cancel）
                'oriwtorderid' => $trade_no, //是,原交易的系统订单号；与 oritradetrace 字段可以二选一上送，如果都上送，以 oritradetrace 节点为准
                'version' => '2', //否,填写的值为 2 时，交易成功后返回优惠信息
            ];
            Log::info('易生支付-交易撤销');
            Log::info($easypay_data);
//            Log::info($this->signKey);
            $res_obj = $this->payment->request($easypay_data, $this->signKey);
            Log::info($res_obj);

            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }

            $res_arr = json_decode($res_obj, true);

            //成功
            if ($res_arr['resultcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => $res_arr['returnmsg'] ?? '撤销成功',
                    'data' => $res_arr,
                ];
            } //TODO：其他码暂不清楚
            else {
                return [
                    'status' => '0',
                    'message' => $res_arr['returnmsg'] ?? 'UNKNOWN',
                    'data' => $res_arr
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-交易撤销-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


    //生成动态二维码(主扫支付) -1 系统错误 0-其他 1-成功 2-待支付
    public function send_qr($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mno'] ?? '';
            $term_id = $data['device_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $trade_amt = isset($total_amount) ? ($total_amount*100) : '';
            $shop_name = $data['shop_name'] ?? '';
            $code = $data['code'] ?? '';
            $notifyurl = $data['notifyurl'] ?? '';
            $pay_type = $data['pay_type'] ?? '';

            if ($pay_type == 'alipay') {
                $opt = 'apPreOrder';
            } elseif ($pay_type == 'weixin') {
                $opt = 'wxPreOrder';
            } elseif ($pay_type == 'unionpay') {
                $opt = 'upPreOrder';
            } else {
                $opt = '';
            }

            $easypay_data = [
                'channelid' => $channel_id, //是,渠道编号
                'merid' => $mer_id, //是,商户编号
                'termid' => $term_id, //是,终端编号
                'tradetrace' => $out_trade_no, //是,商户订单号（控制在 50 位长度以内，确保在请求接口的系统中全局唯一；可以包含数字与字母；不能包含其他特殊字符）
                'opt' => $opt, //是,操作类型（“apPreOrder”：支付宝；“upPreOrder”：银联），根据实际情况选其一
                'tradetype' => 'NATIVE', //支付方式（“NATIVE”）
                'tradeamt' => $trade_amt, //是,交易金额（单位：分）
//                'handingfee' => $handingfee, //否,手续费（以分为单位,第一位是 D 或 C，表示借、贷）
                'body' => $shop_name, //是,商品或支付单简要描述（给用户看）
                'openid' => $code, //支付宝（买家支付宝用户 ID，参考文档 ），上送支付宝用户 ID 时，当前订单仅当前支付宝用户支付
                'notifyurl' => $notifyurl, //客户端接收微信支付成功通知的地址，通知报文请见“后台通知接口”
                'version' => '2', //否,填写的值为 2 时，交易成功后返回优惠信息
            ];
            Log::info('易生支付-主扫支付');
            Log::info($easypay_data);
//            Log::info($this->signKey);
            $res_obj = $this->payment->request($easypay_data, $this->signKey);
            Log::info($res_obj);

            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }

            $res_arr = json_decode($res_obj, true);

            //成功
            if ($res_arr['resultcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => $res_arr['returnmsg'] ?? '交易成功',
                    'code_url' => $res_arr['codeurl'] ?? '', //tradetype 为 NATIVE 时有返回，此参数可直接生成二维码展示出来进行扫码支付；tradetype 为 H5 时有返回：拉起微信支付收银台的中间页面，可通过访问该 url 来拉起微信客户端，完成支付
                    'data' => $res_arr,
                ];
            }
            //待支付
            elseif ($res_arr['resultcode'] == 'AA') {
                return [
                    'status' => '2',
                    'message' => '待支付',
                    'data' => $res_arr,
                ];
            }
            //TODO：其他码暂不清楚
            else {
                return [
                    'status' => '0',
                    'message' => $res_arr['returnmsg'] ?? 'UNKNOWN',
                    'data' => $res_arr
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-主扫支付-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }



public function qr_submit($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mno'] ?? '';
            $term_id = $data['device_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $pay_type = $data['pay_type'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $trade_amt = isset($total_amount) ? ($total_amount*100) : '';
            $shop_name = $data['shop_name'] ?? '';
            $code = $data['code'] ?? '';

            if ($pay_type == 'ALIPAY') {
                $tradeCode = 'WAJS1';
            } else if ('WECHAT' == $pay_type){
                $tradeCode = 'WTJS1';
            }




            $easypay_data = [
                'data' => [
                    'orgBackUrl' => url('/api/easypay/pay_notify_url'),
                    'orgFrontUrl' => url('/page/pay_success'),
                    'payerId' => $code,
                    'tradeAmt' => $trade_amt,
                    'tradeCode' => $tradeCode,
                    'orderInfo' => $shop_name
                ],
                "orgMercode" => $mer_id, //商户号
                "orgTermno" => $term_id, //终端号
                "orgTrace" => $out_trade_no,
            ];



            $base = NewBaseController::getInstance();

            $requestUrl=$base::DOMAIN."/".$base::JS_API_PAY;
            /*
              $res_obj = $base->params($easypay_data, $easypay_data['data'], $data['private_key'], $channel_id)->build($base::MIAN.':'.$base::PROD1.'/'.$base::JS_API_PAY, 'post');
             */
            $res_obj = $base->params($easypay_data, $easypay_data['data'], $data['private_key'], $channel_id)->build($requestUrl, 'post');

//            error_log(date('Y-m-d H:i:s')." 【易生主扫】： ".json_encode([$easypay_data, $res_obj])."\n\n", 3, "/tmp/". 'easypay'.date('Ymd').".log");
            Log::channel("easypay")->info("qr_submit",[
                "url"=>$requestUrl,
                "data"=>$easypay_data,
                "res"=>[$res_obj]
            ]);
//            Log::info('易生支付-静态码提交');
//            Log::info($easypay_data);
//            var_dump($easypay_data);
////            Log::info($this->signKey);
//            $res_obj = $this->payment->request($easypay_data, $this->signKey);
//            Log::info($res_obj);


            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }


            //成功
            if ($res_obj['data']['finRetcode'] == '99') {
                return [
                    'status' => '1',
                    'message' => '交易成功',
                    'data' => $res_obj['data'],
                ];
            }
            //TODO：其他码暂不清楚
            else {
                return [
                    'status' => '0',
                    'message' => $res_obj['data']['appendRetmsg'] ?? 'UNKNOWN',
                    'data' => $res_obj
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-静态码提交-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }

    //静态码提交-公共(公众号/服务窗支付) -1 系统错误 0-其他 1-成功
    public function qr_submit1($data)
    {
        try {
            $channel_id = $data['channel_id'] ?? '';
            $mer_id = $data['mno'] ?? '';
            $term_id = $data['device_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $pay_type = $data['pay_type'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $trade_amt = isset($total_amount) ? ($total_amount*100) : '';
            $shop_name = $data['shop_name'] ?? '';
            $code = $data['code'] ?? '';
            $notify_url = $data['notify_url'] ?? '';

            if ($pay_type == 'ALIPAY') {
                $opt = 'apPreOrder';
            } else{
                $opt = 'wxPreOrder';
            }

            $easypay_data = [
                'channelid' => $channel_id, //是,渠道编号
                'merid' => $mer_id, //是,商户编号
                'termid' => $term_id, //是,终端编号
                'tradetrace' => $out_trade_no, //是,商户订单号（控制在 50 位长度以内，确保在请求接口的系统中全局唯一；可以包含数字与字母；不能包含其他特殊字符）
                'opt' => $opt, //是,操作类型（“wxPreOrder”：微信；“apPreOrder”：支付宝），根据实际情况选其一
                'tradetype' => 'JSAPI', //是,支付方式（“JSAPI”）
                'tradeamt' => $trade_amt, //是,交易金额（单位：分）
                'body' => $shop_name, //是,商品或支付单简要描述（给用户看）
                'openid' => $code, //是,支付宝（买家支付宝用户 ID，参考文档 ）；微信（用户在商户sub_appid[支付的公众号] 下的唯一标识，参考文档 ）
                'notifyurl' => $notify_url, //是,客户端接收微信支付成功通知的地址，通知报文请见“后台通知接口”
//                'handingfee' => $handingfee, //否,手续费（以分为单位,第一位是 D 或 C，表示借、贷）
                'version' => '2', //否,填写的值为 2 时，交易成功后返回优惠信息
            ];
            Log::info('易生支付-静态码提交');
            Log::info($easypay_data);
//            Log::info($this->signKey);
            $res_obj = $this->payment->request($easypay_data, $this->signKey);
            Log::info($res_obj);


            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }

            $res_arr = json_decode($res_obj, true);

            //成功
            if ($res_arr['resultcode'] == '00') {
                return [
                    'status' => '1',
                    'message' => $res_arr['returnmsg'] ?? '交易成功',
                    'data' => $res_arr,
                ];
            } //待支付
            elseif ($res_arr['resultcode'] == 'AA') {
                return [
                    'status' => '2',
                    'message' => $res_arr['returnmsg'] ?? '待支付',
                    'data' => $res_arr,
                ];
            }//TODO：其他码暂不清楚
            else {
                return [
                    'status' => '0',
                    'message' => $res_arr['returnmsg'] ?? 'UNKNOWN',
                    'data' => $res_arr
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-静态码提交-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


    //商户审核结果查询 -1 系统错误 9-待处理；3-待审核；0-审核通过；X-审核失败；1-审核驳回
    public function merchant_query($data)
    {
        try {
            $clientCode = $data['clientCode'] ?? '';
            $merTrace = $data['merTrace'] ?? '';
            $operaTrace = $data['operaTrace'] ?? '';

            $easypay_data = [
                'version' => '1.0',
                'clientCode' => $clientCode, //机构号
                'messageType' => 'QUERYAUDMER',
                'operaTrace' => $operaTrace //原操作流水号
            ];
            if ($merTrace) $easypay_data['merTrace'] = $merTrace; //O,商户唯一标识
            $signature = new Signature($this->signKey);
            $signMac = $signature->sign($easypay_data);
            $easypay_data['MAC'] = md5($signMac); //MAC值???
            Log::info('易生支付-商户审核结果查询');
            Log::info($easypay_data);
//            Log::info($this->signKey);
            $res_obj = $this->payment->request($easypay_data, $this->signKey);
            Log::info($res_obj);

            //系统错误
            if (!$res_obj) {
                return [
                    'status' => '-1',
                    'message' => '系统错误',
                ];
            }

            $res_arr = json_decode($res_obj, true);

            //成功
            if ($res_arr['resultcode'] == '0000') { //9-待处理；3-待审核；0-审核通过；X-审核失败；1-审核驳回
                return [
                    'status' => $res_arr['auditStatus'],
                    'message' => $res_arr['auditMsg'],
                    'data' => $res_arr,
                ];
            } else {
                return [
                    'status' => '-1',
                    'message' => $res_arr['retMsg'],
                    'data' => $res_arr
                ];
            }
        } catch (\Exception $ex) {
            Log::info('易生支付-商户审核结果查询-错误');
            Log::info($ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine());
            return [
                'status' => '-1',
                'message' => $ex->getMessage() .'|'. $ex->getFile() .'|'. $ex->getLine(),
            ];
        }
    }


}
